# coding: utf-8
import json
import os,sys
'''
创建ID和url键值对
    add_json(url)
    get_URL(now_ID)
'''


def format_json():
    js_data = json.dumps(readJson(), indent=4, separators=(',', ':')).encode('utf-8').decode('raw_unicode_escape')
    """把格式化后的数据写入新文件"""
    with open('data.json', 'w') as f:
        f.write(js_data)


def writeJson(temp_str):
    with open('data.json', 'w') as f:
        json.dump(temp_str, f)


def readJson():
    with open('data.json', 'r') as f:  # 解码json
        temp_data = json.load(f)  # 字典格式
        return temp_data


def rwJson(cmd, t_str, w_value=''):
    if cmd == "r":
        temp_data = readJson()
        if t_str in temp_data:
            temp_value = temp_data[t_str]
            return temp_value
        else:
            print(t_str + '不存在！')
            return 'none'
    elif cmd == "w":
        temp_data = readJson()
        temp_data[t_str] = w_value
        writeJson(temp_data)
        print("键值 " + str(t_str) + ":" + temp_data[t_str] + " 写入成功")
        return 'success'
    elif cmd == "rm":
        temp_data = readJson()
        temp_value = temp_data.pop(t_str, 'none')
        writeJson(temp_data)
        print("键值" + str(temp_value) + "已经移除")
        return 'none'
    else:
        print("error cmd!")


def add_json(url):
    last_ID_16 = str(rwJson('r', 'lastID'))
    last_ID_10 = int(hex2dec(last_ID_16))
    this_ID_10 = last_ID_10 + 1
    this_ID_16 = hex(this_ID_10)
    this_ID_16 = this_ID_16.replace('0x', '')
    this_key = 'ID=' + str(this_ID_16)

    this_value = url.replace(' \r', '')

    rwJson('w', this_key, this_value)
    rwJson('w', 'lastID', str(this_ID_16))
    this_url = 'iou.ink/?ID=' + str(this_ID_16)
    format_json()
    return this_url


# json_str = json.dumps(data, indent=4)  # py数据结构 --> json编码的字符串
# data = json.loads(json_str)  # 将json格式数据转换为字典

def get_URL(now_ID):
    temp_data = readJson()
    temp_ID = 'ID=' + str(now_ID)
    if temp_ID in temp_data:
        return rwJson('r', temp_ID)
    else:
        print('ID=' + str(now_ID) + '不存在！')
        return 'none'


def hex2dec(string_num):
    return str(int(string_num.upper(), 16))



if __name__ == '__main__':
    # tmpURL = str(input("url：wwww.sadasdd.com/?q=asdasda&"sadas"/asd"))
    # result_sURL = add_json(tmpURL)
    # print(result_sURL)

    # tmpID = str(input("ID: "))
    result_oURL = get_URL('100001')
    print(result_oURL)
